<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import { cloneDeep } from '@peng_kai/kit/libs/lodash-es';
import { InputPassword } from '~comp/input';
import Turnstile, { cfRules } from '~comp/Turnstile.vue';
import { flzxsqc } from '~/utils';
import { validatePassword } from '../helpers';

export const setPasswordPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./SetPassword.vue')),
  {
    title: computed(() => $t('m23HqsiRn4ZSzHFw33iT')),
    wrapClassName: 'ant-cover__Modal-drawer __screen-drawer',
    rejectOnClose: true,
    width: 400,
    maskClosable: false,
    centered: true,
    footer: null,
  },
);
</script>

<script setup lang="ts">
const emits = defineEmits<{
  close: [];
  confirm: [];
}>();

const form = useAntdForm({
  email: {
    value: '',
    rules: [{ required: true, type: 'email', message: $t('ayjDbPzqAzR5bYomyqC') }],
  },
  email_confirm: {
    value: '',
    rules: [{ validator(_, value) {
      if (!value)
        return formResult($t('xdR1RqEhynjyIdvEBaFn'));
      if (value !== form.state.email)
        return formResult($t('r5iz4uUw3mI0u0sXqKzPf'));
      return formResult();
    } }],
  },
  password: {
    value: '',
    rules: [{ validator: validatePassword }],
  },
  password_confirm: {
    value: '',
    rules: [{ validator(_, value) {
      if (!value)
        return formResult($t('tEk2LUqYvzBMTl7So2p8'));
      if (value !== form.state.password)
        return formResult($t('5Juinv2jAFlT6Jqo3Xwft'));
      return formResult();
    } }],
  },
  cf_turnstile_response: {
    value: '',
    rules: cfRules,
  },
});

const turnstileDomRef = ref();

const userEmailMut = useMutation({
  mutationKey: [apis.apiUserSetEmail.id],
  mutationFn: apis.apiUserSetEmail.setDefaultConfig({
    successMessage: $t('3uiu_6WEzGyEm1YbbT15g'),
    resultType: 'api',
    ignoreCode: [15024],
  }),
  onSuccess(res: any) {
    if (res.code === 15024 || res.code === 0) {
      useUserStore().userInfoQry.refetch();
      emits('confirm');
    }
  },
  onError() {
    turnstileDomRef.value?.reset?.();
    form.$form?.clearValidate?.();
  },
});

const disabled = computed(() => userEmailMut.isPending.value);

async function confirm() {
  const state = await form.$form.validate?.().catch(() => false);
  if (state) {
    const data = cloneDeep(form.state);
    data.password = flzxsqc(form.state.password);
    data.password_confirm = flzxsqc(form.state.password_confirm);
    userEmailMut.mutate({ requestBody: data });
  }
}
</script>

<template>
  <div>
    <AForm v-bind="form.props" class="ant-cover__Form-compact" hideRequiredMark :disabled="disabled" layout="vertical" @finish="confirm()">
      <AFormItem v-bind="form.itemProps.email" :label="$t('wxnfCdf43thnacVZgQa1')">
        <AInput v-model:value="form.state.email" inputmode="email" allowClear :placeholder="$t('zttXb1CiUPpy5BXszb1uP')" />
      </AFormItem>
      <AFormItem v-bind="form.itemProps.email_confirm" :label="$t('lR2ua92RcIsP8Ug0pvHv1')">
        <AInput v-model:value="form.state.email_confirm" inputmode="email" allowClear :isCanPaste="false" :placeholder="$t('rPer4xDanTfZb97tUdZ')" />
      </AFormItem>
      <AFormItem v-bind="form.itemProps.password" :label="$t('ph7eJFfBmsn7xFyvj8')">
        <InputPassword v-model:value="form.state.password" :placeholder="$t('hwbK7ZZedFNtXjMoargn')" />
      </AFormItem>
      <AFormItem v-bind="form.itemProps.password_confirm" :label="$t('mrEblLvgr1ZXcaYe5EAbZ')">
        <InputPassword v-model:value="form.state.password_confirm" :placeholder="$t('s3xfpONkuEYwOqOirexaS')" />
      </AFormItem>
      <AFormItem v-bind="form.itemProps.cf_turnstile_response">
        <Turnstile ref="turnstileDomRef" v-model:value="form.state.cf_turnstile_response" />
      </AFormItem>

      <AButton
        class="ant-cover__Button-3d-primary mb-0 mt-4 !sticky" htmlType="submit"
        type="primary" block :disabled="disabled" :loading="disabled"
      >
        {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
      </AButton>
    </AForm>
  </div>
</template>
